import React, { useState, useEffect } from 'react';
import {
  Table,
  Card,
  Button,
  Space,
  Tag,
  Modal,
  Form,
  Input,
  Select,
  DatePicker,
  message,
  Popconfirm,
  Drawer,
  Descriptions,
  Progress,
  Avatar,
  Tooltip,
  Row,
  Col,
  Statistic,
  Tabs,
  Timeline,
  Upload,
  Divider
} from 'antd';
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  EyeOutlined,
  PlayCircleOutlined,
  PauseCircleOutlined,
  CheckCircleOutlined,
  ClockCircleOutlined,
  ExclamationCircleOutlined,
  UserOutlined,
  CalendarOutlined,
  FileTextOutlined,
  UploadOutlined,
  DownloadOutlined,
  FilterOutlined,
  ReloadOutlined
} from '@ant-design/icons';
import { ColumnsType } from 'antd/es/table';
import dayjs from 'dayjs';
import type { RcFile } from 'antd/es/upload';
import { taskService } from '../services/taskService';
import { userService } from '../services/userService';
import { workflowService } from '../services/workflowService';

const { Option } = Select;
const { TextArea } = Input;
const { TabPane } = Tabs;
const { RangePicker } = DatePicker;

interface Task {
  id: string;
  title: string;
  description: string;
  type: string;
  category: string;
  status: 'created' | 'assigned' | 'in_progress' | 'suspended' | 'completed' | 'cancelled' | 'rejected';
  priority: number;
  assigneeId: string;
  assigneeName: string;
  createdBy: string;
  createdByName: string;
  updatedBy?: string;
  updatedByName?: string;
  businessKey?: string;
  businessType?: string;
  businessData?: Record<string, any>;
  processInstanceId?: string;
  processDefinitionId?: string;
  processDefinitionKey?: string;
  processTaskId?: string;
  formId?: string;
  formDataId?: string;
  startTime?: string;
  dueTime?: string;
  completedTime?: string;
  createdAt: string;
  updatedAt: string;
  tags?: string;
  tagList?: string[];
  remark?: string;
  extend?: Record<string, any>;
  sort?: number;
  deleted?: boolean;
  tenantId?: string;
  candidateUsers?: string[];
  candidateGroups?: string[];
  duration?: number;
  overdue?: boolean;
  remainingTime?: number;
}

interface TaskComment {
  id: string;
  content: string;
  author: string;
  authorAvatar?: string;
  createdAt: string;
}

interface TaskHistory {
  id: string;
  action: string;
  description: string;
  operator: string;
  createdAt: string;
}

export default function TaskManagement() {
  const [tasks, setTasks] = useState<Task[]>([]);
  const [loading, setLoading] = useState(false);
  const [modalLoading, setModalLoading] = useState(false);
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [isDetailDrawerVisible, setIsDetailDrawerVisible] = useState(false);
  const [editingTask, setEditingTask] = useState<Task | null>(null);
  const [selectedTask, setSelectedTask] = useState<Task | null>(null);
  const [taskComments, setTaskComments] = useState<TaskComment[]>([]);
  const [taskHistory, setTaskHistory] = useState<TaskHistory[]>([]);
  const [form] = Form.useForm();
  const [commentForm] = Form.useForm();
  const [searchText, setSearchText] = useState('');
  const [statusFilter, setStatusFilter] = useState<string>('');
  const [priorityFilter, setPriorityFilter] = useState<string>('');
  const [assigneeFilter, setAssigneeFilter] = useState<string>('');
  
  // 字典数据状态
  const [taskTypes, setTaskTypes] = useState<string[]>([]);
  const [taskCategories, setTaskCategories] = useState<string[]>([]);
  const [users, setUsers] = useState<any[]>([]);
  const [workflows, setWorkflows] = useState<any[]>([]);

  useEffect(() => {
    loadTasks();
    loadDictionaryData();
  }, []);

  // 加载字典数据
  const loadDictionaryData = async () => {
    try {
      const [typesRes, categoriesRes, usersRes, workflowsRes] = await Promise.all([
        taskService.getTaskTypes(),
        taskService.getTaskCategories(),
        userService.getUsers({ page: 0, size: 100 }),
        workflowService.getWorkflows({ page: 0, size: 100 })
      ]);
      
      setTaskTypes(typesRes || []);
      setTaskCategories(categoriesRes || []);
      setUsers(usersRes.content || []);
      setWorkflows(workflowsRes.content || []);
    } catch (error) {
      console.error('加载字典数据失败:', error);
      // 如果接口失败，使用默认数据
      setTaskTypes(['manual', 'workflow', 'system', 'approval']);
      setTaskCategories(['general', 'development', 'testing', 'deployment']);
    }
  };

  const loadTasks = async () => {
    setLoading(true);
    try {
      const response = await taskService.getTasks({
        page: 0,
        size: 20,
        status: statusFilter || undefined,
        priority: undefined,
        keyword: searchText || undefined
      });
      setTasks(response.content || []);
    } catch (error: any) {
      console.error('加载任务列表失败:', error);
      
      if (error.response) {
        const { status } = error.response;
        switch (status) {
          case 403:
            message.error('没有权限访问任务列表');
            break;
          case 500:
            message.error('服务器内部错误，请稍后再试');
            break;
          default:
            message.error(error.response.data?.message || '加载任务列表失败');
        }
      } else {
        message.error('网络连接失败，请检查网络设置');
      }
    } finally {
      setLoading(false);
    }
  };

  const loadTaskDetails = async (taskId: string) => {
    try {
      const [comments, history] = await Promise.all([
        taskService.getTaskComments(taskId),
        taskService.getTaskHistory(taskId)
      ]);
      
      setTaskComments(comments);
      setTaskHistory(history);
    } catch (error: any) {
      console.error('加载任务详情失败:', error);
      
      if (error.response) {
        const { status } = error.response;
        switch (status) {
          case 403:
            message.error('没有权限访问任务详情');
            break;
          case 404:
            message.error('任务不存在或已被删除');
            break;
          case 500:
            message.error('服务器内部错误，请稍后再试');
            break;
          default:
            message.error(error.response.data?.message || '加载任务详情失败');
        }
      } else {
        message.error('网络连接失败，请检查网络设置');
      }
    }
  };

  const handleCreate = () => {
    setEditingTask(null);
    setIsModalVisible(true);
    form.resetFields();
  };

  const handleEdit = (task: Task) => {
    setEditingTask(task);
    setIsModalVisible(true);
    form.setFieldsValue({
      ...task,
      dueDate: dayjs(task.dueDate)
    });
  };

  const handleDelete = async (id: string) => {
    try {
      await taskService.deleteTask(id);
      setTasks(tasks.filter(task => task.id !== id));
      message.success('删除成功');
    } catch (error) {
      console.error('删除失败:', error);
      message.error('删除失败');
    }
  };

  const handleBatchDelete = async () => {
    try {
      await taskService.batchDeleteTasks(selectedRowKeys as string[]);
      setTasks(tasks.filter(task => !selectedRowKeys.includes(task.id)));
      setSelectedRowKeys([]);
      message.success('批量删除成功');
    } catch (error) {
      console.error('批量删除失败:', error);
      message.error('批量删除失败');
    }
  };

  const handleStatusChange = async (id: string, status: string) => {
    try {
      const updatedTask = await taskService.updateTaskStatus(id, status);
      setTasks(tasks.map(task => 
        task.id === id ? updatedTask : task
      ));
      message.success('状态更新成功');
    } catch (error) {
      console.error('状态更新失败:', error);
      message.error('状态更新失败');
    }
  };

  const handleViewDetails = (task: Task) => {
    setSelectedTask(task);
    setIsDetailDrawerVisible(true);
    loadTaskDetails(task.id);
  };

  const handleModalOk = async () => {
    try {
      setModalLoading(true);
      const values = await form.validateFields();
      
      // 准备任务数据
      const taskData = {
        title: values.title,
        description: values.description,
        type: values.type,
        category: values.category,
        priority: values.priority,
        assigneeId: values.assigneeId,
        assigneeName: users.find(u => u.id === values.assigneeId)?.name || '',
        dueTime: values.dueDate ? values.dueDate.format('YYYY-MM-DD HH:mm:ss') : undefined,
        tags: values.tags || [],
        remark: values.remark,
        businessKey: values.businessKey,
        businessType: values.businessType,
        processDefinitionKey: values.workflowId
      };

      if (editingTask) {
        // 更新任务
        const updatedTask = await taskService.updateTask(editingTask.id, taskData);
        setTasks(tasks.map(task => 
          task.id === editingTask.id ? updatedTask : task
        ));
        message.success('任务更新成功');
      } else {
        // 创建任务
        const newTask = await taskService.createTask(taskData);
        setTasks([newTask, ...tasks]);
        message.success('任务创建成功');
      }

      setIsModalVisible(false);
      form.resetFields();
      setEditingTask(null);
    } catch (error) {
      console.error('任务操作失败:', error);
      message.error(editingTask ? '任务更新失败' : '任务创建失败');
    } finally {
      setModalLoading(false);
    }
  };

  const handleAddComment = async () => {
    try {
      const values = await commentForm.validateFields();
      const newComment: TaskComment = {
        id: Date.now().toString(),
        content: values.content,
        author: '当前用户',
        authorAvatar: '',
        createdAt: dayjs().format('YYYY-MM-DD HH:mm:ss')
      };
      
      setTaskComments([...taskComments, newComment]);
      commentForm.resetFields();
      message.success('评论添加成功');
    } catch (error) {
      console.error('添加评论失败:', error);
    }
  };

  const getStatusColor = (status: string) => {
    switch (status) {
      case 'created': return 'default';
      case 'assigned': return 'orange';
      case 'in_progress': return 'blue';
      case 'suspended': return 'yellow';
      case 'completed': return 'green';
      case 'cancelled': return 'red';
      case 'rejected': return 'red';
      default: return 'default';
    }
  };

  const getStatusText = (status: string) => {
    switch (status) {
      case 'created': return '已创建';
      case 'assigned': return '已分配';
      case 'in_progress': return '进行中';
      case 'suspended': return '已暂停';
      case 'completed': return '已完成';
      case 'cancelled': return '已取消';
      case 'rejected': return '已驳回';
      default: return '未知';
    }
  };

  const getPriorityColor = (priority: number) => {
    switch (priority) {
      case 1: return 'green';
      case 2: return 'blue';
      case 3: return 'orange';
      case 4: return 'red';
      case 5: return 'red';
      default: return 'default';
    }
  };

  const getPriorityText = (priority: number) => {
    switch (priority) {
      case 1: return '最低';
      case 2: return '低';
      case 3: return '中';
      case 4: return '高';
      case 5: return '最高';
      default: return '未知';
    }
  };

  const filteredTasks = tasks.filter(task => {
    const matchesSearch = !searchText || 
      task.title.toLowerCase().includes(searchText.toLowerCase()) ||
      task.description.toLowerCase().includes(searchText.toLowerCase()) ||
      task.assigneeName.toLowerCase().includes(searchText.toLowerCase());
    
    const matchesStatus = !statusFilter || task.status === statusFilter;
    const matchesPriority = !priorityFilter || task.priority.toString() === priorityFilter;
    const matchesAssignee = !assigneeFilter || task.assigneeName === assigneeFilter;
    
    return matchesSearch && matchesStatus && matchesPriority && matchesAssignee;
  });

  const columns: ColumnsType<Task> = [
    {
      title: '任务名称',
      dataIndex: 'title',
      key: 'title',
      width: 200,
      render: (text, record) => (
        <div>
          <div className="font-medium">{text}</div>
          {record.processDefinitionKey && (
            <div className="text-xs text-gray-500">流程: {record.processDefinitionKey}</div>
          )}
          {record.type && (
            <div className="text-xs text-gray-400">类型: {record.type}</div>
          )}
        </div>
      )
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status) => (
        <Tag color={getStatusColor(status)}>
          {getStatusText(status)}
        </Tag>
      )
    },
    {
      title: '优先级',
      dataIndex: 'priority',
      key: 'priority',
      width: 80,
      render: (priority) => (
        <Tag color={getPriorityColor(priority)}>
          {getPriorityText(priority)}
        </Tag>
      )
    },
    {
      title: '负责人',
      dataIndex: 'assigneeName',
      key: 'assigneeName',
      width: 120,
      render: (assigneeName, record) => (
        <div className="flex items-center space-x-2">
          <Avatar 
            icon={<UserOutlined />} 
            size="small"
          />
          <span>{assigneeName}</span>
        </div>
      )
    },
    {
      title: '类别',
      dataIndex: 'category',
      key: 'category',
      width: 100,
      render: (category) => (
        <Tag>{category}</Tag>
      )
    },
    {
      title: '截止日期',
      dataIndex: 'dueTime',
      key: 'dueTime',
      width: 120,
      render: (dueTime, record) => {
        if (!dueTime) return '-';
        const isOverdue = record.overdue;
        return (
          <span className={isOverdue ? 'text-red-500' : ''}>
            {dayjs(dueTime).format('YYYY-MM-DD')}
            {isOverdue && <ExclamationCircleOutlined className="ml-1 text-red-500" />}
          </span>
        );
      }
    },
    {
      title: '标签',
      dataIndex: 'tagList',
      key: 'tagList',
      width: 150,
      render: (tagList) => (
        <div>
          {tagList && tagList.map((tag: string) => (
            <Tag key={tag}>{tag}</Tag>
          ))}
        </div>
      )
    },
    {
      title: '操作',
      key: 'action',
      width: 200,
      render: (_, record) => (
        <Space size="small">
          <Tooltip title="查看详情">
            <Button 
              type="text" 
              icon={<EyeOutlined />} 
              onClick={() => handleViewDetails(record)}
            />
          </Tooltip>
          <Tooltip title="编辑">
            <Button 
              type="text" 
              icon={<EditOutlined />} 
              onClick={() => handleEdit(record)}
            />
          </Tooltip>
          {record.status === 'assigned' && (
            <Tooltip title="开始">
              <Button 
                type="text" 
                icon={<PlayCircleOutlined />} 
                onClick={() => handleStatusChange(record.id, 'in_progress')}
              />
            </Tooltip>
          )}
          {record.status === 'in_progress' && (
            <Tooltip title="暂停">
              <Button 
                type="text" 
                icon={<PauseCircleOutlined />} 
                onClick={() => handleStatusChange(record.id, 'suspended')}
              />
            </Tooltip>
          )}
          {(record.status === 'in_progress' || record.status === 'suspended') && (
            <Tooltip title="完成">
              <Button 
                type="text" 
                icon={<CheckCircleOutlined />} 
                onClick={() => handleStatusChange(record.id, 'completed')}
              />
            </Tooltip>
          )}
          {record.status === 'in_progress' && (
            <Tooltip title="驳回">
              <Button 
                type="text" 
                icon={<CloseCircleOutlined />} 
                onClick={() => handleStatusChange(record.id, 'rejected')}
              />
            </Tooltip>
          )}
          <Popconfirm
            title="确定要删除这个任务吗？"
            onConfirm={() => handleDelete(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Tooltip title="删除">
              <Button 
                type="text" 
                danger 
                icon={<DeleteOutlined />}
              />
            </Tooltip>
          </Popconfirm>
        </Space>
      )
    }
  ];

  const rowSelection = {
    selectedRowKeys,
    onChange: (newSelectedRowKeys: React.Key[]) => {
      setSelectedRowKeys(newSelectedRowKeys);
    }
  };

  const taskStats = {
    total: tasks.length,
    created: tasks.filter(t => t.status === 'created').length,
    assigned: tasks.filter(t => t.status === 'assigned').length,
    in_progress: tasks.filter(t => t.status === 'in_progress').length,
    suspended: tasks.filter(t => t.status === 'suspended').length,
    completed: tasks.filter(t => t.status === 'completed').length,
    cancelled: tasks.filter(t => t.status === 'cancelled').length,
    rejected: tasks.filter(t => t.status === 'rejected').length,
    overdue: tasks.filter(t => t.overdue || (t.dueTime && dayjs(t.dueTime).isBefore(dayjs(), 'day'))).length
  };

  return (
    <div className="p-6">
      {/* 统计卡片 */}
      <Row gutter={[16, 16]} className="mb-6">
        <Col xs={24} sm={12} lg={4}>
          <Card>
            <Statistic
              title="总任务数"
              value={taskStats.total}
              prefix={<FileTextOutlined />}
              valueStyle={{ color: '#1890ff' }}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} lg={4}>
          <Card>
            <Statistic
              title="已创建"
              value={taskStats.created}
              prefix={<ClockCircleOutlined />}
              valueStyle={{ color: '#faad14' }}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} lg={4}>
          <Card>
            <Statistic
              title="已分配"
              value={taskStats.assigned}
              prefix={<UserOutlined />}
              valueStyle={{ color: '#1890ff' }}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} lg={4}>
          <Card>
            <Statistic
              title="进行中"
              value={taskStats.in_progress}
              prefix={<PlayCircleOutlined />}
              valueStyle={{ color: '#52c41a' }}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} lg={4}>
          <Card>
            <Statistic
              title="已完成"
              value={taskStats.completed}
              prefix={<CheckCircleOutlined />}
              valueStyle={{ color: '#52c41a' }}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} lg={4}>
          <Card>
            <Statistic
              title="已驳回"
              value={taskStats.rejected}
              prefix={<ExclamationCircleOutlined />}
              valueStyle={{ color: '#ff4d4f' }}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} lg={4}>
          <Card>
            <Statistic
              title="已逾期"
              value={taskStats.overdue}
              prefix={<CalendarOutlined />}
              valueStyle={{ color: '#ff4d4f' }}
            />
          </Card>
        </Col>
      </Row>

      {/* 主要内容 */}
      <Card>
        <div className="mb-4">
          <div className="flex justify-between items-center mb-4">
            <h2 className="text-xl font-semibold">任务管理</h2>
            <Space>
              <Button 
                type="primary" 
                icon={<PlusOutlined />} 
                onClick={handleCreate}
              >
                新建任务
              </Button>
              {selectedRowKeys.length > 0 && (
                <Popconfirm
                  title={`确定要删除选中的 ${selectedRowKeys.length} 个任务吗？`}
                  onConfirm={handleBatchDelete}
                  okText="确定"
                  cancelText="取消"
                >
                  <Button danger icon={<DeleteOutlined />}>
                    批量删除
                  </Button>
                </Popconfirm>
              )}
              <Button icon={<ReloadOutlined />} onClick={loadTasks}>
                刷新
              </Button>
            </Space>
          </div>
          
          {/* 筛选器 */}
          <Row gutter={[16, 16]} className="mb-4">
            <Col xs={24} sm={12} md={6}>
              <Input.Search
                placeholder="搜索任务名称、描述或负责人"
                value={searchText}
                onChange={(e) => setSearchText(e.target.value)}
                allowClear
              />
            </Col>
            <Col xs={24} sm={12} md={4}>
              <Select
                placeholder="状态筛选"
                value={statusFilter}
                onChange={setStatusFilter}
                allowClear
                className="w-full"
              >
                <Option value="created">已创建</Option>
                <Option value="assigned">已分配</Option>
                <Option value="in_progress">进行中</Option>
                <Option value="suspended">已暂停</Option>
                <Option value="completed">已完成</Option>
                <Option value="cancelled">已取消</Option>
                <Option value="rejected">已驳回</Option>
              </Select>
            </Col>
            <Col xs={24} sm={12} md={4}>
              <Select
                placeholder="优先级筛选"
                value={priorityFilter}
                onChange={setPriorityFilter}
                allowClear
                className="w-full"
              >
                <Option value="1">最低</Option>
                <Option value="2">低</Option>
                <Option value="3">中</Option>
                <Option value="4">高</Option>
                <Option value="5">最高</Option>
              </Select>
            </Col>
            <Col xs={24} sm={12} md={4}>
              <Select
                placeholder="负责人筛选"
                value={assigneeFilter}
                onChange={setAssigneeFilter}
                allowClear
                className="w-full"
              >
                <Option value="张三">张三</Option>
                <Option value="李四">李四</Option>
                <Option value="王五">王五</Option>
                <Option value="赵六">赵六</Option>
              </Select>
            </Col>
          </Row>
        </div>

        <Table
          columns={columns}
          dataSource={filteredTasks}
          rowKey="id"
          rowSelection={rowSelection}
          loading={loading}
          pagination={{
            total: filteredTasks.length,
            pageSize: 10,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total, range) => 
              `第 ${range[0]}-${range[1]} 条，共 ${total} 条`
          }}
          scroll={{ x: 1200 }}
        />
      </Card>

      {/* 创建/编辑任务模态框 */}
      <Modal
        title={editingTask ? '编辑任务' : '新建任务'}
        open={isModalVisible}
        onOk={handleModalOk}
        onCancel={() => setIsModalVisible(false)}
        confirmLoading={modalLoading}
        width={600}
        okText="确定"
        cancelText="取消"
      >
        <Form
          form={form}
          layout="vertical"
          initialValues={{
            status: 'created',
            priority: 3,
            type: 'manual',
            category: 'general'
          }}
        >
          <Form.Item
            name="title"
            label="任务名称"
            rules={[{ required: true, message: '请输入任务名称' }]}
          >
            <Input placeholder="请输入任务名称" />
          </Form.Item>
          
          <Form.Item
            name="description"
            label="任务描述"
            rules={[{ required: true, message: '请输入任务描述' }]}
          >
            <TextArea rows={3} placeholder="请输入任务描述" />
          </Form.Item>
          
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="type"
                label="任务类型"
                rules={[{ required: true, message: '请选择任务类型' }]}
              >
                <Select placeholder="请选择任务类型">
                  {taskTypes.map(type => (
                    <Option key={type} value={type}>{type}</Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="category"
                label="任务类别"
                rules={[{ required: true, message: '请选择任务类别' }]}
              >
                <Select placeholder="请选择任务类别">
                  {taskCategories.map(category => (
                    <Option key={category} value={category}>{category}</Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
          </Row>
          
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="status"
                label="状态"
                rules={[{ required: true, message: '请选择状态' }]}
              >
                <Select placeholder="请选择状态">
                  <Option value="created">已创建</Option>
                  <Option value="assigned">已分配</Option>
                  <Option value="in_progress">进行中</Option>
                  <Option value="suspended">已暂停</Option>
                  <Option value="completed">已完成</Option>
                  <Option value="cancelled">已取消</Option>
                  <Option value="rejected">已驳回</Option>
                </Select>
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="priority"
                label="优先级"
                rules={[{ required: true, message: '请选择优先级' }]}
              >
                <Select placeholder="请选择优先级">
                  <Option value={1}>最低</Option>
                  <Option value={2}>低</Option>
                  <Option value={3}>中</Option>
                  <Option value={4}>高</Option>
                  <Option value={5}>最高</Option>
                </Select>
              </Form.Item>
            </Col>
          </Row>
          
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="assigneeId"
                label="负责人"
                rules={[{ required: true, message: '请选择负责人' }]}
              >
                <Select placeholder="请选择负责人">
                  {users.map(user => (
                    <Option key={user.id} value={user.id}>{user.username}</Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="dueDate"
                label="截止日期"
              >
                <DatePicker 
                  className="w-full" 
                  placeholder="请选择截止日期" 
                  showTime
                  format="YYYY-MM-DD HH:mm:ss"
                />
              </Form.Item>
            </Col>
          </Row>
          
          <Form.Item
            name="remark"
            label="备注"
          >
            <TextArea rows={2} placeholder="请输入备注信息" />
          </Form.Item>
          
          <Form.Item
            name="workflowName"
            label="关联工作流"
          >
            <Select placeholder="请选择关联工作流" allowClear>
              {workflows.map(workflow => (
                <Option key={workflow.id} value={workflow.name}>{workflow.name}</Option>
              ))}
            </Select>
          </Form.Item>
          
          <Form.Item
            name="tags"
            label="标签"
          >
            <Select
              mode="tags"
              placeholder="请输入标签"
              tokenSeparators={[',']}
            >
              {/* 允许用户自由输入标签，同时提供一些预设选项 */}
            </Select>
          </Form.Item>
        </Form>
      </Modal>

      {/* 任务详情抽屉 */}
      <Drawer
        title="任务详情"
        placement="right"
        width={600}
        open={isDetailDrawerVisible}
        onClose={() => setIsDetailDrawerVisible(false)}
      >
        {selectedTask && (
          <Tabs defaultActiveKey="details">
            <TabPane tab="基本信息" key="details">
              <Descriptions column={1} bordered>
                <Descriptions.Item label="任务名称">
                  {selectedTask.title}
                </Descriptions.Item>
                <Descriptions.Item label="任务描述">
                  {selectedTask.description}
                </Descriptions.Item>
                <Descriptions.Item label="任务类型">
                  <Tag>{selectedTask.type}</Tag>
                </Descriptions.Item>
                <Descriptions.Item label="任务类别">
                  <Tag>{selectedTask.category}</Tag>
                </Descriptions.Item>
                <Descriptions.Item label="状态">
                  <Tag color={getStatusColor(selectedTask.status)}>
                    {getStatusText(selectedTask.status)}
                  </Tag>
                </Descriptions.Item>
                <Descriptions.Item label="优先级">
                  <Tag color={getPriorityColor(selectedTask.priority)}>
                    {getPriorityText(selectedTask.priority)}
                  </Tag>
                </Descriptions.Item>
                <Descriptions.Item label="负责人">
                  <div className="flex items-center space-x-2">
                    <Avatar 
                      icon={<UserOutlined />} 
                      size="small"
                    />
                    <span>{selectedTask.assigneeName}</span>
                  </div>
                </Descriptions.Item>
                <Descriptions.Item label="创建人">
                  {selectedTask.createdByName}
                </Descriptions.Item>
                <Descriptions.Item label="业务键">
                  {selectedTask.businessKey || '无'}
                </Descriptions.Item>
                <Descriptions.Item label="流程实例ID">
                  {selectedTask.processInstanceId || '无'}
                </Descriptions.Item>
                <Descriptions.Item label="流程定义">
                  {selectedTask.processDefinitionKey || '无'}
                </Descriptions.Item>
                <Descriptions.Item label="开始时间">
                  {selectedTask.startTime ? dayjs(selectedTask.startTime).format('YYYY-MM-DD HH:mm:ss') : '未开始'}
                </Descriptions.Item>
                <Descriptions.Item label="完成时间">
                  {selectedTask.completedTime ? dayjs(selectedTask.completedTime).format('YYYY-MM-DD HH:mm:ss') : '未完成'}
                </Descriptions.Item>
                <Descriptions.Item label="截止时间">
                  {selectedTask.dueTime ? (
                    <span className={selectedTask.overdue ? 'text-red-500' : ''}>
                      {dayjs(selectedTask.dueTime).format('YYYY-MM-DD HH:mm:ss')}
                      {selectedTask.overdue && <ExclamationCircleOutlined className="ml-1" />}
                    </span>
                  ) : '无'}
                </Descriptions.Item>
                <Descriptions.Item label="创建时间">
                  {dayjs(selectedTask.createdAt).format('YYYY-MM-DD HH:mm:ss')}
                </Descriptions.Item>
                <Descriptions.Item label="更新时间">
                  {dayjs(selectedTask.updatedAt).format('YYYY-MM-DD HH:mm:ss')}
                </Descriptions.Item>
                <Descriptions.Item label="标签">
                  {selectedTask.tagList && selectedTask.tagList.map(tag => (
                    <Tag key={tag}>{tag}</Tag>
                  ))}
                </Descriptions.Item>
                <Descriptions.Item label="备注">
                  {selectedTask.remark || '无'}
                </Descriptions.Item>
                <Descriptions.Item label="附件">
                  {selectedTask.attachments && selectedTask.attachments.length > 0 ? (
                    <div>
                      {selectedTask.attachments.map((file, index) => (
                        <div key={index} className="flex items-center space-x-2 mb-1">
                          <FileTextOutlined />
                          <span>{file}</span>
                          <Button type="link" size="small" icon={<DownloadOutlined />}>
                            下载
                          </Button>
                        </div>
                      ))}
                    </div>
                  ) : (
                    '无附件'
                  )}
                </Descriptions.Item>
              </Descriptions>
            </TabPane>
            
            <TabPane tab="评论" key="comments">
              <div className="mb-4">
                <Form form={commentForm} onFinish={handleAddComment}>
                  <Form.Item
                    name="content"
                    rules={[{ required: true, message: '请输入评论内容' }]}
                  >
                    <TextArea 
                      rows={3} 
                      placeholder="请输入评论内容" 
                    />
                  </Form.Item>
                  <Form.Item>
                    <Button type="primary" htmlType="submit">
                      添加评论
                    </Button>
                  </Form.Item>
                </Form>
              </div>
              
              <Divider />
              
              <div>
                {taskComments.map(comment => (
                  <div key={comment.id} className="mb-4 p-3 bg-gray-50 rounded">
                    <div className="flex items-center space-x-2 mb-2">
                      <Avatar 
                        src={comment.authorAvatar} 
                        icon={<UserOutlined />} 
                        size="small"
                      />
                      <span className="font-medium">{comment.author}</span>
                      <span className="text-gray-500 text-sm">{comment.createdAt}</span>
                    </div>
                    <div>{comment.content}</div>
                  </div>
                ))}
              </div>
            </TabPane>
            
            <TabPane tab="操作历史" key="history">
              <Timeline>
                {taskHistory.map(item => (
                  <Timeline.Item key={item.id}>
                    <div>
                      <div className="font-medium">{item.action}</div>
                      <div className="text-gray-600">{item.description}</div>
                      <div className="text-gray-500 text-sm">
                        {item.operator} · {item.createdAt}
                      </div>
                    </div>
                  </Timeline.Item>
                ))}
              </Timeline>
            </TabPane>
          </Tabs>
        )}
      </Drawer>
    </div>
  );
}